<template>
  <div id="container" ref="container">
    <div id="tabbar" ref="tabbar">
      <ul ref="tablist" id="tablist">
        <!-- <li class="add_newtab" ref="add_newtab" @click="createNewTab">+</li> -->
        <li class="add_newtab" ref="add_newtab" @click="newTab">+</li>
      </ul>
      <ul id="ctrl_list">
        <li id="minimizeWin" @click="min_win" v-html="icon.frame.min"></li>
        <li id="toggleWin" @click="toggle_win" v-html="win_isMax ? icon.frame.restore : icon.frame.max"></li>
        <li id="closeWin" @click="close_win" v-html="icon.frame.close"></li>
      </ul>
    </div>
    <div id="toolbar"></div>
  </div>
</template>

<script setup>
import { onMounted, shallowRef, ref } from 'vue'
import { ws } from '@/modules/websocket'
import { icon } from '@/assets/icon/icons'

const tabbar = ref(null)
const tablist = ref(null)
const add_newtab = ref(null)
const container = ref(null)

// 窗体是否最大化
const win_isMax = shallowRef(false)

let webSocketServer_win = null
let webSocketServer_tab = null

// 监听端口，打开新页触发
window.wss.config()
  .then(config => {
    const socket = new WebSocket(`ws://localhost:${config.tab.port}/listener`)

    socket.onopen = () => {
      socket.send(JSON.stringify({
        event: 'connect'
      }))
    }

    socket.onmessage = event => {
      const msg = JSON.parse(event.data).msg
      if (msg.url) {
        let isRewrite = false
        $('.tab').each((i, e) => {
          if (e.getAttribute('wid') == msg.wid) {
            e.querySelector('p').innerText = msg.title
            isRewrite = true
          }
        })
        if (!isRewrite) {
          createNewTab({
            ...msg,
            current: true
          })
        }
      } else {
        createNewTab()
      }
    }
  })

// 

window.wss.config()
  .then(config => {
    const socket = new WebSocket(`ws://localhost:${config.tab.port}/newtab`)
    webSocketServer_tab = socket
  })

window.wss.config()
  .then(config => {
    const socket = new WebSocket(`ws://localhost:${config.frame.port}/ws`)
    webSocketServer_win = socket

    socket.onopen = () => {
      ws_win(socket)
    }
  })

function ws_win(socket) {
  //#region 窗体移动监听
  tabbar.value.addEventListener('mousedown', e => {
    const bound = {
      width: window.innerWidth,
      height: window.innerHeight
    }

    e.target.id == 'tabbar' ? (() => {
      // 
      const originX = e.pageX
      const originY = e.pageY

      function move(e) {
        // 开始移动
        if (!win_isMax.value) {
          socket.send(JSON.stringify({
            event: 'set-mainWinPos',
            msg: { x: e.screenX - originX, y: e.screenY - originY, ...bound }
          }))
        }
      }
      function stop() {
        // 停止监听
        document.documentElement.removeEventListener('mousemove', move)
        // socket.close()
      }
      document.documentElement.addEventListener('mousemove', move)
      document.documentElement.addEventListener('mouseup', stop)
    })() : null
  })
  //#endregion
}

onMounted(() => {
  // keep()

  // 报告标签页的高度
  $(() => window.wss.config()
    .then(config => {
      ws(config.frame.port, {
        event: 'tabbar-height',
        msg: $(container.value).outerHeight()
      })
        .then(wss => {
          keep()
          wss.close()
        })
    }))

  // for (let i = 0; i < 10; i++) {
  //   createNewTab({ current: false })
  // }

})

// 关闭窗口
function close_win() {
  webSocketServer_win.send(JSON.stringify({
    event: 'close_win'
  }))
}

function toggle_win() {
  webSocketServer_win.send(JSON.stringify({
    event: 'toggle_win'
  }))

  webSocketServer_win.onmessage = event => {
    const res = JSON.parse(event.data)

    // 
    if (res?.msg?.frameState == 'max') {
      win_isMax.value = true
    } else if (res?.msg?.frameState == 'restore') {
      win_isMax.value = false
    }
  }
}

function min_win() {
  webSocketServer_win.send(JSON.stringify({
    event: 'min_win'
  }))
}

function keep(ifkeep) {
  tablist.value.querySelector('li.tab') ?? newTab()
}

function createNewTab({ title = '新建标签页', url = '/newTab.html', current = true, wid } = {}) {
  $('.tab.current').removeClass('current')
  const wrap = $(`<li wid="${wid}" url="${url}"></li>`)
  const tit = $(`<p>${title}</p>`)
  const close = $('<span>\u00D7</span></span>')

  wrap.append(tit)

  wrap.addClass(['tab', current == true ? 'current' : ''])
  close.addClass('close')

  $(tablist.value).append(wrap)
  wrap.append(close)

  wrap.on('click', () => {
    $('.tab.current').removeClass('current')
    wrap.addClass('current')

    webSocketServer_tab.send(JSON.stringify({
      event: 'show-current-frame',
      wid: wid
    }))
  })

  // add_newtab.value.style.left = Array.from($('li')).map(e => $(e).outerWidth()).reduce((acc, curr) => acc + curr, 0) + 'px'

  // newTab(url)

  // 删除标签页
  close.on('click', () => {
    webSocketServer_tab.send(JSON.stringify({
      event: 'close-current-frame',
      wid: wid
    }))

    // 自动定位到上一个标签页，如果有
    $(wrap).prev('.tab').trigger('click')

    wrap.remove()
    keep()
  })
}

// 创建新页面
function newTab({ url = null } = {}) {
  webSocketServer_tab.send(JSON.stringify({
    event: 'new-tab',
    msg: { url }
  }))
}
window.createNewTab = createNewTab
</script>

<style lang="less">
* {
  margin: 0;
  padding: 0;
}

html {
  font-size: 24px;
}

#container {
  cursor: default;
  background: #ddf0f6;
  height: 3.6rem;
}

#tabbar {
  background: #9dcbd8;
  display: flex;
  justify-content: space-between
}

#tablist {
  position: relative;
  display: flex;
  align-items: flex-end;
  white-space: nowrap;
  overflow: hidden;
  height: 1.8rem;
  user-select: none;
  // padding-left: 1rem;

  >li {
    @fontsize: 0.6rem;

    display: inline-block;
    font: 400 @fontsize auto;
    // margin-left: 0.1rem;
    padding: 0.3rem 0.4rem;
    border-radius: 0.5rem 0.5rem 0 0;

    &.add_newtab {
      position: relative;
    }

    .close,
    &.add_newtab {
      font: 800 @fontsize auto;
    }

    &.tab {
      display: flex;

      &.current {
        background: #ddf0f6;
      }

      .close {
        display: inline-block;
        padding: 0 @fontsize * .24;
        margin-left: 1rem;

        &:hover {
          background: #00000022;
        }

      }
    }

    &:hover {
      background: #ffffff33;
    }

  }
}
</style>

<style lang="less">
#ctrl_list {
  display: flex;

  >* {
    height: 100%;
    width: 1.5rem;
    // background: #000;

    display: flex;
    justify-content: center;

    .icon {
      // background: #ccc;
      width: 0.5rem;
      vertical-align: middle;
    }
  }
}

#minimizeWin,
#toggleWin {
  &:hover {
    background: #ffffff66;
  }
}

#closeWin {
  &:hover {
    background: #d25353;
  }
}
</style>